package com.bw.launcher.navgraph

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.navigation.NavController
import androidx.navigation.NavGraph
import androidx.navigation.NavGraphNavigator
import androidx.navigation.Navigator
import androidx.navigation.fragment.FragmentNavigator
import com.bw.widget.navigation.DestinationEntity
import com.bw.widget.navigation.ShowNavigator
import com.bw.widget.navigation.UIApplication

/**
 * 创建navigation导航
 * object: NavigationBuilder->创建一个类NavigationBuilder->并实例化对象->饿汉式单例
 * 匿名内部类 object : 接口(){}->实例化得对象
 * */
object NavigationBuilder {

    //构建navigation导航
    fun builder(
        activity:AppCompatActivity,
        manager : FragmentManager,
        controller : NavController,
        constaintId: Int
    ){
        //NavigatorProvider存储导航器
        val provider = controller.navigatorProvider
        //构建NavGraph->根据导航器中provider存放得导航信息设置给
        //controller->controller绑定bottomview-》id-》切换
        val navGraph = NavGraph(NavGraphNavigator(provider))
        //创建shownavigator->替换原有得fragmentnavigator->改变原有fragment切换逻辑
        val fragmentNavigator = ShowNavigator(activity,manager,constaintId)
        provider.addNavigator(fragmentNavigator)
        //获取json解析出来得Hashmap 根据key获取对应DestinationEntity对象
        //创建navigation下得fragment得destination
        val map = UIApplication.destinationes
        val iterator = map!!.keys.iterator()
        //迭代构建destination
        while (iterator.hasNext()){
            val entity : DestinationEntity = map.get(iterator.next())!!
            //构建DestinationEntity
            val destination : FragmentNavigator.Destination =
                fragmentNavigator.createDestination()
            destination.id = entity.id
            destination.className = entity.className!!
            destination.addDeepLink(entity.pageUrl!!)
            navGraph.addDestination(destination)
            if (entity.asStarter){
                //默认显示得fragment
                navGraph.startDestination = entity.id
            }
        }
        controller.setGraph(navGraph)//设置导航器
    }


}